package cn.qidisoft.edu.hzjt.controller.zyc;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.Semester;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.zyc.PartyBranch;
import cn.qidisoft.edu.hzjt.model.zyc.PartyBranchStar;
import cn.qidisoft.edu.hzjt.model.zyc.PartyBranchStarScore;
import cn.qidisoft.edu.hzjt.model.zyc.PartyLeagueMember;
import cn.qidisoft.edu.hzjt.service.ICommonService;
import cn.qidisoft.edu.hzjt.service.zyc.IDyService;
import cn.qidisoft.edu.hzjt.service.zyc.IDzbService;
import cn.qidisoft.edu.hzjt.service.zyc.IPartyBranchStarService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/**
 * 
 * @author a 星级支部考核控制器
 * 
 */
@Controller
@RequestMapping("/partyBranchStar")
public class PartyBranchStarController {
	protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);
	@Autowired
	private IPartyBranchStarService partyBranchStarService;

	@Autowired
	private IDzbService dzbService;
	
	@Autowired
	private IDyService dyService;
	
	 @Autowired
	 private ICommonService commonService;
	
	/**
	 * 跳列表页面
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model) {
		List<Semester> semesters = partyBranchStarService.querySemesterList();
		model.addAttribute("data", semesters);
		return "zyc/partyBranchStar/list";
	}

	/**
	 * 
	 * 分页查看所有表格信息
	 */
	@RequestMapping(value = "/listData")
	@ResponseBody
	public ResponseResult slePartyBranchStar(ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage, PartyBranchStar partyBranchStar) {
		try {
			// 得到当前的党员id
			// UserEmployee userEmployee = (UserEmployee)
			// request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			// PartyLeagueMember partyLeagueMember =
			// partyBranchStarService.selDzbId(userEmployee.getEmid());
			// Integer getdZBID = partyLeagueMember.getdZBID();
			// partyBranchStar.setDzbid(getdZBID);

			Map<String, Object> queryMap = new HashMap<String, Object>();
			String dZBMC = request.getParameter("dZBMC");
			String khnd = request.getParameter("khnd");
			if (request.getParameter("begintime") != null || request.getParameter("endtime") != null) {
				if (request.getParameter("begintime") != "" && request.getParameter("endtime") != "") {
					queryMap.put("begintime", Integer.parseInt(request.getParameter("begintime")));
					queryMap.put("endtime", Integer.parseInt(request.getParameter("endtime")));
				}
			}
			queryMap.put("dZBMC", dZBMC);
			queryMap.put("khnd", khnd);
			Page page = new Page();
			page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
			page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
			BaseController.setSortByColumn(request, "khid", "asc");
			partyBranchStar.setOrderField((String) request.getAttribute("orderField"));
			partyBranchStar.setOrderFlag((String) request.getAttribute("orderFlag"));			
			queryMap.put("partyBranchStar", partyBranchStar);
			PaginationBean<PartyBranchStar> paginationBean = partyBranchStarService
					.queryPartyBranchStarPageList(queryMap, page);
			ResponseResult result = new ResponseResult();
			result.setTotal(paginationBean.getTotalRecords());
			result.setRows(paginationBean.getPageList());
			return result;
		} catch (Exception e) {

		}
		return null;
	}

	/**
	 * 跳增加页面
	 */
	@RequestMapping(value = "/preadd")
	public String preadd(Model model) {
		List<PartyBranch> allDzbinfo = dzbService.getAllDzbinfo(new PartyBranch());
		model.addAttribute("data", allDzbinfo);
		return "zyc/partyBranchStar/add";
	}

	/**
	 * 查询分数 修改后的
	 */
	@RequestMapping(value = "/selZbdyfs2")
	@ResponseBody
	public Map<String, Object> selZbdyfs2(HttpServletRequest request, Model model, @Param("year") String year,
			@Param("dzbid") Integer dzbid) {
		Map<String, Object> queryMap2 = new HashMap<String, Object>();
		PartyBranchStar partyBranchStar2 = new PartyBranchStar();
		partyBranchStar2.setDzbid(dzbid);
		partyBranchStar2.setKhnd(Integer.parseInt(year));
		PartyBranchStar partyBranchStar1 = partyBranchStarService.selStarsByYearAndDzbid(partyBranchStar2);
		// 判断是否已经添加了这个年份和党支部的数据
		if (partyBranchStar1 != null) {
			queryMap2.put("isExist", "1");
			return queryMap2;
		}
		// 根据年份和id查询前一年的星级
		PartyBranchStar partyBranchStar = new PartyBranchStar();
		partyBranchStar.setDzbid(dzbid);
		partyBranchStar.setKhnd(Integer.parseInt(year) - 1);
		PartyBranchStar pStar = partyBranchStarService.selStarsByYearAndDzbid(partyBranchStar);
		if (pStar == null) {
			queryMap2.put("stars", 3);
		} else {
			queryMap2.put("stars", pStar.getStars());
		}
		// 查询分数的
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("year", Integer.parseInt(year));
		queryMap.put("dzbid", dzbid);
		List<PartyBranchStarScore> partyBranchStarScores = partyBranchStarService.selScore(queryMap);
		if (partyBranchStarScores.size() == 0) {
			queryMap2.put("score1", 0);
			queryMap2.put("score2", 0);
			queryMap2.put("avgScore", 0);
		} else if (partyBranchStarScores.size() == 1) {
			String xq = partyBranchStarScores.get(0).getSxh().substring(
					partyBranchStarScores.get(0).getSxh().length() - 1, partyBranchStarScores.get(0).getSxh().length());
			Double score = partyBranchStarScores.get(0).getTatalScore();
			if (xq.equals("1")) {
				queryMap2.put("score1", score);
				queryMap2.put("score2", 0);
				queryMap2.put("avgScore", score / 2);
			} else {
				queryMap2.put("score1", 0);
				queryMap2.put("score2", score);
				queryMap2.put("avgScore", score / 2);
			}
		} else {
			Double score1 = partyBranchStarScores.get(0).getTatalScore();
			Double score2 = partyBranchStarScores.get(1).getTatalScore();
			if (score1 == null && score2 == null) {
				queryMap2.put("score1", 0);
				queryMap2.put("score2", 0);
				queryMap2.put("avgScore", 0);
			} else if (score1 != null && score2 != null) {
				queryMap2.put("score1", score1);
				queryMap2.put("score2", score2);
				queryMap2.put("avgScore", (score1 + score2) / 2);
			} else if (score1 == null && score2 != null) {
				queryMap2.put("score1", 0);
				queryMap2.put("score2", score2);
				queryMap2.put("avgScore", score2 / 2);
			} else if (score1 != null && score2 == null) {
				queryMap2.put("score1", score1);
				queryMap2.put("score2", 0);
				queryMap2.put("avgScore", score1 / 2);
			}
		}
		return queryMap2;
	}

	/**
	 * 个人查询分数
	 */
	@RequestMapping(value = "/selZbdyfs3")
	@ResponseBody
	public Map<String, Object> selZbdyfs3(HttpServletRequest request, Model model, @Param("year") String year,
			@Param("dzbid") Integer dzbid) {
		Map<String, Object> queryMap2 = new HashMap<String, Object>();
		PartyBranchStar partyBranchStar2 = new PartyBranchStar();
		partyBranchStar2.setDzbid(dzbid);
		partyBranchStar2.setKhnd(Integer.parseInt(year));
		PartyBranchStar partyBranchStar1 = partyBranchStarService.selStarsByYearAndDzbid(partyBranchStar2);
		// 判断是否已经添加了这个年份和党支部的数据
		if (partyBranchStar1 == null) {
			queryMap2.put("isExist", "0");
			return queryMap2;
		}
		queryMap2.put("partyBranchStar", partyBranchStar1);
		return queryMap2;
	}

	/**
	 * 增加数据
	 */
	@RequestMapping(value = "/add")
	public String add(ModelMap model, HttpServletRequest request, PartyBranchStar data) {
		data.setGid("1");
		partyBranchStarService.insert(data);
		model.put("data", data);
		Integer dzbid = data.getDzbid();
		PartyBranch dzbById = dzbService.getDzbById(dzbid);
		model.put("dzb", dzbById);
		String action = request.getParameter("action");
		if (action.equals("1")) {
			return "redirect:./info?khid=" + data.getKhid();
		} else if (action.equals("2")) {
			return "redirect:./preadd";
		}
		return null;
	}

	/**
	 * 跳view頁面
	 */
	@RequestMapping(value = "/info")
	public String info(HttpServletRequest request, Model model) {
		String khid = request.getParameter("khid");
		// 根据考核id得到单个党支部信息
		PartyBranchStar partyBranchStar = partyBranchStarService
				.selPartyBranchStarWithPartyBranch(Integer.parseInt(khid));
		List<PartyBranch> allDzbinfo = dzbService.getAllDzbinfo(new PartyBranch());

		PartyBranch dzbById = dzbService.getDzbById(partyBranchStar.getDzbid());
		model.addAttribute("dzb", dzbById);
		request.setAttribute("data", allDzbinfo);
		request.setAttribute("data", partyBranchStar);
		return "zyc/partyBranchStar/view";
	}

	/**
	 * 跳修改页面
	 */
	@RequestMapping(value = "/updateUI")
	public String updateUI(Model model, @Param("khid") Integer khid) {
		PartyBranchStar partyBranchStar = partyBranchStarService.selPartyBranchStarWithPartyBranch(khid);
		List<PartyBranch> allDzbinfo = dzbService.getAllDzbinfo(new PartyBranch());
		model.addAttribute("dzbsel", allDzbinfo);
		model.addAttribute("data", partyBranchStar);
		PartyBranch dzbById = dzbService.getDzbById(partyBranchStar.getDzbid());
		model.addAttribute("dzb", dzbById);
		return "zyc/partyBranchStar/update";
	}

	/**
	 * 跳个人信息查看页面
	 */
	@RequestMapping(value = "/viewGr")
	public String viewGr(ModelMap model, @Param("dYID") Integer dYID,HttpServletRequest request) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatStr = formatter.format(new Date());
        UserEmployee user = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        formatStr = formatStr.substring(0, 4);
        // 根据empid 获取党员id
        // 根据党员id获取党支部id
		PartyLeagueMember pMember = new PartyLeagueMember();
		pMember.setgH(user.getEmid()+"");
		PartyLeagueMember partyLeagueMember = dyService.getDzbId(pMember);
		Integer khid = 0;
		if(null != partyLeagueMember) {
			PartyBranchStar pStar = new PartyBranchStar();
			pStar.setDzbid(partyLeagueMember.getdZBID());
			pStar.setKhnd(Integer.parseInt(formatStr));
			PartyBranchStar pStar2 = partyBranchStarService.getStar(pStar);
			if(null != pStar2) {
				khid = pStar2.getKhid();				
			}
		}
		PartyBranchStar partyBranchStar = partyBranchStarService.selPartyBranchStarWithPartyBranch(khid);
		List<PartyBranch> allDzbinfo = dzbService.getAllDzbinfo(new PartyBranch());
		model.addAttribute("dzbsel", allDzbinfo);
		model.addAttribute("data", partyBranchStar);
		PartyBranch dzbById = null;
		if(null != partyBranchStar) {
			dzbById = dzbService.getDzbById(partyBranchStar.getDzbid());			
		}
		model.addAttribute("dzb", dzbById);
		return "zyc/partyBranchStar/viewGr";
	}
    
	/**
	 * 修改数据
	 */
	@RequestMapping(value = "update")
	public String update(HttpServletRequest request, Model model, PartyBranchStar data) {
		System.out.println("aaaaaaaaaaaaaaaaaaaaa" + data.toString());
		data.setGid("1");
		data.setDzbid(Integer.parseInt(request.getParameter("dzbid")));
		partyBranchStarService.update(data);
		model.addAttribute("data", data);
		String action = request.getParameter("action");
		if (action.equals("1")) {
			return "redirect:./info?khid=" + data.getKhid();
		} else if (action.equals("2")) {
			return "redirect:./preadd";
		}
		return null;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/delete")
	public String Delete(HttpServletRequest request) {
		String stringIdList = request.getParameter("idList");
		List<Integer> id_List = new ArrayList<>();
		if (stringIdList.contains(",")) {
			String idlist[] = stringIdList.split(",");
			for (String lists : idlist) {
				id_List.add(Integer.parseInt(lists));
			}
			partyBranchStarService.deleteByIds(id_List);
		} else {
			id_List.add(Integer.parseInt(stringIdList));
			partyBranchStarService.deleteByIds(id_List);
		}
		return "redirect:./list";
	}

	/**
	 * 导出数据
	 */
	@RequestMapping(value = "export")
	public @ResponseBody void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			Map<String, Object> qMap = new HashMap<String, Object>();
			qMap.put("khnd", request.getParameter("khnd"));
			qMap.put("dZBMC", request.getParameter("dZBMC"));
			if (request.getParameter("begintime") != "") {
				qMap.put("begintime", Integer.parseInt(request.getParameter("begintime")));
			} else {
				qMap.put("begintime", null);
			}
			if (request.getParameter("endtime") != "") {
				qMap.put("endtime", Integer.parseInt(request.getParameter("endtime")));
			} else {
				qMap.put("endtime", null);
			}
			List<PartyBranchStar> datalist = partyBranchStarService.getDASList(qMap);
			String[][] title_name = { { "党支部名称", "党支部书记", "考核年度", "支部党员先锋指数上半年总分", "支部党员先锋指数下半年总分", "支部党员先锋指数全年平均值",
					"民主测评情况", "总支委员会考核情况", "其他考核情况", "星级" } };
			String[] title_style = { "hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25",
					"hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25", "kt_12_bold_18", "kt_12_bold_18",
					"kt_12_bold_18" };
			String fileName = "星级支部考核";
			String[] remark = { "" };
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (datalist != null && !datalist.isEmpty()) {
				for (PartyBranchStar res : datalist) {
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("dzbmc", res.getPartyBranch().getdZBMC());
					map.put("dzbsjid", res.getPartyBranch().getdZBSJID());
					map.put("khnd", res.getKhnd());
					map.put("sbnzf", res.getSbnzf());
					map.put("xbnzf", res.getXbnzf());
					map.put("qnpjz", res.getQnpjz());
					map.put("mzcpqk", res.getMzcpqk());
					map.put("zzwyhkhqk", res.getZzwyhkhqk());
					map.put("qtkhqk", res.getQtkhqk());
					map.put("stars", res.getStars());
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
			try {
				String filenameConvert = "星级支部考核";
				new String(fileName.getBytes("GB2312"), "ISO8859-1");
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
			}
		} catch (RPCException e) {
			LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
		}
	}
}
